import { getBillAllByDay } from '@/services';
import {
  ActionSheet,
  Button,
  CalendarPicker,
  Card,
  Collapse,
  DatePicker,
  Grid,
  List,
  Modal,
  Selector,
} from 'antd-mobile';
import { CloseOutline, FilterOutline } from 'antd-mobile-icons';
import type { Action } from 'antd-mobile/es/components/action-sheet';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import { history, useModel } from 'umi';
import styles from './index.less';
const min = new Date(2022, 0, 1);

export default function HomePage() {
  const [visible, setVisible] = useState(false);
  const [visible1, setVisible1] = useState<boolean>(false);
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [currentMonth, setCurrentMonth] = useState<string>(
    dayjs().format('YYYY年 - MM月'),
  );
  const [sumData, setSumData] = useState<any>({});
  const [billData, setBillData] = useState<any>([]);
  const { transactionTypes, geTtransactionTypeValue } =
    useModel('useTransactionType');

  const [visible2, setVisible2] = useState(false);
  const [startTime, setStartTime] = useState<string>(
    dayjs().format('YYYY-MM-DD'),
  );
  const [endTime, setEndTime] = useState<string>(dayjs().format('YYYY-MM-DD'));
  const [payType, setPayType] = useState<string[]>([]);
  const [type, setType] = useState<string[]>([]);
  const [transactionType, setTransactionType] = useState<any>();
  const actions: Action[] = transactionTypes
    ? transactionTypes.map((item: { key: any; value: any }) => {
        return {
          key: item.key,
          text: item.value,
        };
      })
    : [];

  const getBillAllByDayFunc = (params: any) => {
    getBillAllByDay(params)
      .then((res) => {
        console.log(res);
        if (res.data) {
          setSumData(res.data.sum);
          setBillData(res.data.data);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  const getPayTypeValue = (key: number) => {
    return key === 1 ? '支付宝' : '微信';
  };
  const getTypeSymbol = (key: number) => {
    let symbol = '';
    if (key === 1) {
      symbol = '+';
    } else if (key === 2) {
      symbol = '-';
    }
    return symbol;
  };

  const defaultRange: [Date, Date] = [
    dayjs().subtract(2, 'day').toDate(),
    dayjs().toDate(),
  ];
  useEffect(() => {
    getBillAllByDayFunc({ month: dayjs().format('YYYY-MM') });
  }, []);

  return (
    <div className={styles.container}>
      <Modal
        title="筛选"
        visible={modalVisible}
        content={
          <List>
            <List.Item
              style={{ fontSize: '0.8rem' }}
              onClick={() => {
                setVisible2(true);
              }}
            >
              <span>日期：</span>
              <span>{`${startTime}~${endTime}`}</span>
            </List.Item>
            <List.Item
              style={{ fontSize: '0.8rem' }}
              onClick={() => {
                setVisible(true);
              }}
              extra={
                transactionType ? (
                  <CloseOutline
                    onClick={(e) => {
                      e.stopPropagation();
                      setTransactionType(null);
                    }}
                  />
                ) : null
              }
            >
              <span>支付方式：</span>
              <span>{geTtransactionTypeValue(transactionType as number)} </span>
            </List.Item>
            <List.Item style={{ display: 'flex', fontSize: '0.8rem' }}>
              <span>支付平台：</span>
              <Selector
                // columns={3}
                multiple
                options={[
                  {
                    label: '支付宝',
                    value: '1',
                  },
                  {
                    label: '微信',
                    value: '2',
                  },
                ]}
                defaultValue={['1']}
                onChange={(arr) => {
                  setPayType(arr);
                }}
              />
            </List.Item>
            <List.Item style={{ display: 'flex', fontSize: '0.8rem' }}>
              <span>类型：</span>
              <Selector
                // columns={3}
                multiple
                options={[
                  {
                    label: '收入',
                    value: '1',
                  },
                  {
                    label: '支出',
                    value: '2',
                  },
                  {
                    label: '不计收支',
                    value: '3',
                  },
                ]}
                defaultValue={['1']}
                onChange={(arr) => {
                  setType(arr);
                }}
              />
            </List.Item>
          </List>
        }
        actions={[
          {
            key: 'confirm',
            text: '确认',
            primary: true,
            onClick: () => {
              console.log(startTime);
              console.log(type);
              console.log(transactionType);
              console.log(payType);
              getBillAllByDayFunc({
                startTime,
                endTime,
                type,
                transactionType,
                payType,
              });
              setModalVisible(false);
            },
          },
          {
            key: 'cancel',
            text: '取消',
            onClick: () => {
              setModalVisible(false);
            },
          },
        ]}
      />
      <CalendarPicker
        min={min}
        // max={max}
        visible={visible2}
        defaultValue={defaultRange}
        // value={[dayjs(startTime).toDate(), dayjs(endTime).toDate()]}
        selectionMode="range"
        popupStyle={{ zIndex: '9999' }}
        onClose={() => {
          setVisible2(false);
        }}
        onConfirm={(val) => {
          setStartTime(dayjs(val ? val[0] : '').format('YYYY-MM-DD'));
          setEndTime(dayjs(val ? val[1] : '').format('YYYY-MM-DD'));
          setVisible2(false);
        }}
      />
      <ActionSheet
        visible={visible}
        actions={actions}
        popupClassName={styles.actionSheet}
        cancelText="取消"
        style={{
          height: '35rem',
          overflow: 'auto',
          zIndex: '9999',
        }}
        onClose={() => setVisible(false)}
        onAction={(action) => {
          console.log(action);
          setTransactionType(action.key as number);
          setVisible(false);
        }}
      />
      <Card style={{ marginBottom: '1rem' }}>
        <Grid columns={5} gap={8}>
          <Grid.Item span={4}>
            <div>
              <Button
                onClick={() => {
                  setVisible1(true);
                }}
              >
                {currentMonth}
              </Button>
            </div>
          </Grid.Item>
          <Grid.Item
            style={{ display: 'flex', alignItems: 'center', fontSize: '1rem' }}
            onClick={(e) => {
              e.stopPropagation();
              setModalVisible(true);
            }}
          >
            <div>
              <FilterOutline />
              筛选
            </div>
          </Grid.Item>
        </Grid>
        <DatePicker
          visible={visible1}
          onClose={() => {
            setVisible1(false);
          }}
          precision="month"
          onConfirm={(val) => {
            setCurrentMonth(dayjs(val).format('YYYY年 - MM月'));
            getBillAllByDayFunc({ month: dayjs(val).format('YYYY-MM') });
          }}
        />
      </Card>
      <Card style={{ marginBottom: '1rem' }}>
        <List header="汇总">
          <List.Item>
            <Grid columns={2} gap={8}>
              <Grid.Item>
                <span style={{ fontWeight: 'bold' }}>支出：</span>
                {sumData.expenditure_total}
              </Grid.Item>
              <Grid.Item>
                <div>
                  <span style={{ fontWeight: 'bold' }}>收入：</span>
                  {sumData && sumData.inCome_total}
                </div>
              </Grid.Item>
            </Grid>
          </List.Item>
          <List.Item>
            <Grid columns={1}>
              <Grid.Item>
                <span style={{ fontWeight: 'bold' }}>不计入收支：</span>
                {sumData && sumData.not_counting_total}
              </Grid.Item>
            </Grid>
          </List.Item>
          <Collapse defaultActiveKey={['1']}>
            <Collapse.Panel
              key="1"
              title="支付宝微信汇总"
              style={{ fontWeight: 'bold' }}
            >
              <List.Item>
                <p className={styles.listItemTitle}>支付宝</p>
                <Grid columns={2} gap={8}>
                  <Grid.Item>
                    <span style={{ fontWeight: 'bold' }}>支出：</span>
                    {sumData && sumData.alipay_expenditure_total}
                  </Grid.Item>
                  <Grid.Item>
                    <div>
                      <span style={{ fontWeight: 'bold' }}>收入：</span>
                      {sumData && sumData.alipay_income_total}
                    </div>
                  </Grid.Item>
                </Grid>
              </List.Item>
              <List.Item>
                <p className={styles.listItemTitle}>微信</p>
                <Grid columns={2} gap={8}>
                  <Grid.Item>
                    <span style={{ fontWeight: 'bold' }}>支出：</span>
                    {sumData && sumData.wechat_expenditure_total}
                  </Grid.Item>
                  <Grid.Item>
                    <div>
                      <span style={{ fontWeight: 'bold' }}>收入：</span>
                      {sumData && sumData.wechat_income_total}
                    </div>
                  </Grid.Item>
                </Grid>
              </List.Item>
            </Collapse.Panel>
          </Collapse>
        </List>
      </Card>
      {billData.length
        ? billData.map((item) => (
            // <>
            <Card
              style={{ marginBottom: '1rem' }}
              key={item.payDay}
              className={styles.listItem}
            >
              <List header={item.payDay}>
                <List.Item>
                  <Grid columns={2} gap={8} style={{ fontSize: '1rem' }}>
                    <Grid.Item>
                      <span style={{ fontWeight: 'bold' }}>支出：</span>
                      {item.expenditure_total}
                    </Grid.Item>
                    <Grid.Item>
                      <div>
                        <span style={{ fontWeight: 'bold' }}>收入：</span>
                        {item.inCome_total}
                      </div>
                    </Grid.Item>
                  </Grid>
                </List.Item>
                {item.children.length
                  ? item.children.map((itm: any) => (
                      <List.Item
                        key={itm.id}
                        onClick={(e) => {
                          e.stopPropagation();
                          history.push(`/billDetail?id=${itm.id}`);
                        }}
                      >
                        <Grid columns={5} gap={8} style={{ fontSize: '1rem' }}>
                          <Grid.Item span={3}>
                            <div style={{ fontWeight: 'bold' }}>
                              {geTtransactionTypeValue(itm.transactionType)}
                              <span
                                style={{
                                  paddingLeft: '1rem',
                                  fontSize: '0.8rem',
                                  color: '#bbb',
                                }}
                              >
                                {' '}
                                {itm.payTime}
                              </span>
                            </div>
                            <div
                              className={styles.ellipsis}
                            >{`${getPayTypeValue(itm.payType)} ${
                              itm.notes
                            }`}</div>
                          </Grid.Item>
                          <Grid.Item
                            span={2}
                            style={{
                              fontWeight: 'bold',
                              fontSize: '1.1rem',
                              textAlign: 'right',
                            }}
                          >
                            {`${getTypeSymbol(itm.type)} ${itm.money}`}
                          </Grid.Item>
                        </Grid>
                      </List.Item>
                    ))
                  : null}
              </List>
            </Card>
            // </>
          ))
        : null}
    </div>
  );
}
